<?php

namespace app\common\dao\system;

use app\common\model\system\SystemConfigValue as model;
use app\common\dao\BaseDao;

class SystemConfigValueDao extends BaseDao
{
    /**
    * 设置模型
    * @return model
    */
    protected function getModel(): string
    {
        return model::class;
    }

    public function mUpdate($type, string $key, array $data)
    {
        if (isset($data['value'])) $data['value'] = json_encode($data['value']);
        return ($this->getModel())::getDB()->where('type', $type)->where('config_key', $key)->update($data);
    }

    public function fields(array $keys,string $type)
    {
        $result = ($this->getModel())::getDB()->whereIn('config_key', $keys)->where('type', $type)->withAttr('value', function ($val, $data) {
            return json_decode($val, true);
        })->column('value', 'config_key');
        foreach ($result as $k => $val) {
            $result[$k] = json_decode($val, true);
        }
        return $result;
    }

    public function clear(array $keys, string $type)
    {
        return ($this->getModel())::getDB()->whereIn('config_key', $keys)->where('type', $type)->delete();
    }


    public function value(string $key, string $type)
    {
        $value = ($this->getModel())::getDB()->where('config_key', $key)->where('type', $type)->value('value');
        $value = is_null($value) ? null : json_decode($value, true);
        return $value;
    }

    public function mExists(string $key, string $type): bool
    {
        return ($this->getModel())::getDB()->where('config_key', $key)->where('type', $type)->count() > 0;
    }


}